package com.oms.web.comet4j;

import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.comet4j.core.CometConnection;
import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;
import org.comet4j.core.event.ConnectEvent;
import org.comet4j.core.listener.ConnectListener;
import org.springframework.stereotype.Component;

import com.oms.domain.Acknowledgement;
import com.oms.service.UserService;
import com.oms.web.comet4j.HelloWorld.HelloAppModule;

@Component
public class MessageComet  implements ServletContextListener {
	
	@Resource
	UserService userService;
	
	@Resource
	Acknowledgement acknowledgement;
	
	private static final String CHANNEL = "userComet";

	@Override
	public void contextInitialized(ServletContextEvent sce) {
        CometContext cc = CometContext.getInstance();
        cc.registChannel(CHANNEL);
        Thread helloAppModule = new Thread(new HelloAppModule(), "Sender App Module");
        helloAppModule.setDaemon(true);
        helloAppModule.start();
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		
	}

    class HelloAppModule implements Runnable {
        public void run() {
                while (true) {
                        try {
                                Thread.sleep(1000);
                        } catch (Exception ex) {
                                ex.printStackTrace();
                        }
                        CometEngine engine = CometContext.getInstance().getEngine();
                        engine.sendToAll(CHANNEL, 1);
                }
        }
    }
    
    class LoginListener extends ConnectListener {
        @Override
        public boolean handleEvent(ConnectEvent anEvent) {
        		CometEngine engine =anEvent.getTarget();
                CometConnection conn = anEvent.getConn();
                CometContext.getInstance().getEngine().sendTo("userComet", engine.getConnection(conn.getId()),"欢迎上线");
                
                return true;
        }
    }

}
